package woa.sort.test20230210;

import java.util.Arrays;

/**
 * 递推公式：merge_sort(p…r) = merge(merge_sort(p…q), merge_sort(q+1…r))
 * 终止条件：p >= r 不用再继续分解
 *
 * @author wangpeng
 * @date 2023/2/15 21:42
 */
public class MergeSort1 {

    public static void sort(int[] arr, int p, int r) {
        if (p >= r) {
            return;
        }
        int q = p + (r - p) / 2;
        sort(arr, p, q);
        sort(arr, q + 1, r);
        merge(arr, p, q, r);
    }

    public static void merge(int[] arr, int p, int q, int r) {
        int[] temp = new int[r - p + 1];
        int j = p, k = q + 1;
        for (int i = 0; i < temp.length; i++) {
            if (j == q + 1) {
                temp[i] = arr[k];
                k++;
                continue;
            }

            if (k == r + 1) {
                temp[i] = arr[j];
                j++;
                continue;
            }

            if (arr[j] <= arr[k]) {
                temp[i] = arr[j];
                j++;
            } else {
                temp[i] = arr[k];
                k++;
            }
        }

        for (int i = 0; i <= r - p; ++i) {
            arr[p + i] = temp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {3,4,1,3,5,6,78,1,3,3,3,2};
        sort(arr,0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}
